package com.yly.plugindemo;

import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.yly.com.CommonRes;

import dalvik.system.DexClassLoader;

public class MainActivity extends AppCompatActivity {
public static final String PLUGIN1= "plugin1";
public static final String PLUGIN2= "plugin2";
	private TextView title;
	private ImageView contentImg;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		title = findViewById(R.id.title_tv);
		contentImg = findViewById(R.id.content_img);
		AssetUtils.extractInfo(getBaseContext(),PLUGIN1);
		AssetUtils.extractInfo(getBaseContext(),PLUGIN2);
	}

	@Override
	public AssetManager getAssets() {
		return AssetUtils.sAssetManager==null ? super.getAssets():AssetUtils.sAssetManager;
	}

	@Override
	public Resources getResources() {
		return AssetUtils.sResources==null?super.getResources():AssetUtils.sResources;
	}
	private static final String TAG ="MainActivity";
	public void chosePlugin1(View view) {
		/**
		 * 1. 添加打Path中
		 * 2. 通知 DexClassLoader 去加载这个类
		 * */
		AssetUtils.addAssetPath(getBaseContext(),PLUGIN1);
		PluginInfo pluginInfo = AssetUtils.pluginInfos.get(PLUGIN1);
		DexClassLoader classLoader = pluginInfo.getClassLoader();
		try {
			// 他会去指定目录下查找
			Class<?> aClass = classLoader.loadClass("com.yly.plugin1.ResImp");
			CommonRes commonRes = (CommonRes) aClass.newInstance();
			String text = commonRes.getText();
			title.setText(text);
			int drawableRid = commonRes.getDrawable();
			Drawable drawable = getResources().getDrawable(drawableRid);
			contentImg.setImageDrawable(drawable);
		} catch (Exception e) {
			e.printStackTrace();
			Log.e(TAG, "chosePlugin1: load fail.",e);
		}
	}

	public void chosePlugin2(View view) {
		AssetUtils.addAssetPath(getBaseContext(),PLUGIN2);
		PluginInfo pluginInfo = AssetUtils.pluginInfos.get(PLUGIN2);
		DexClassLoader classLoader = pluginInfo.getClassLoader();
		try {
			// 他会去指定目录下查找
			Class<?> aClass = classLoader.loadClass("com.yly.plugin2.ResImp");
			CommonRes commonRes = (CommonRes) aClass.newInstance();
			String text = commonRes.getText();
			title.setText(text);
			int drawableRid = commonRes.getDrawable();
			Drawable drawable = getResources().getDrawable(drawableRid);
			contentImg.setImageDrawable(drawable);
		} catch (Exception e) {
			e.printStackTrace();
			Log.e(TAG, "chosePlugin2: load fail.",e);
		}
	}
}
